package com.smz.controller;

import com.smz.entity.Functions;
import com.smz.service.FunctionsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
public class FunctionsController {


    @Autowired
    private FunctionsService functionsService;

    @GetMapping("/functions/username")
    public ResponseEntity<List<Functions>> findAllFunctions(){
        //通过security里的securityContextHolder获取上下文在获取用户
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal!=null){
            List<Functions> functions = functionsService.selectFunctionsByName(principal.getUsername());
            return ResponseEntity.ok(functions);
        }
        return null;
    }

    @GetMapping("/functions")
    public ResponseEntity<List<Functions>> findFunctions(){
        List<Functions> functions = functionsService.selectAllFunctions();
        return ResponseEntity.ok(functions);
    }
    @GetMapping("/findAll")
    public ResponseEntity<List<Functions>> findAll(){
        List<Functions> functions = functionsService.findAll();
        return ResponseEntity.ok(functions);
    }
    @GetMapping("/functions/role/{roleId}")
    public ResponseEntity<List<Functions>> findFunctionsByRoleId(@PathVariable("roleId") Integer id){
        List<Functions> functions = functionsService.selectByRoleId(id);
        return ResponseEntity.ok(functions);
    }

    @PostMapping("/function")
    public ResponseEntity<String> addFunction(@RequestBody Functions functions){
        functionsService.addFunction(functions);
        return ResponseEntity.ok("ok");
    }

    @PutMapping("/function")
    public ResponseEntity<String> modifyFunction(@RequestBody Functions functions){
        functionsService.modifyFunction(functions);
        return ResponseEntity.ok("ok");
    }
    @DeleteMapping("/function/{id}")
    public ResponseEntity<String> deleteFunction(@PathVariable("id") Integer id){
        functionsService.removeFunction(id);
        return ResponseEntity.ok("ok");
    }
}
